import { Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { VirtualCharacter } from './virtual-character.entity';
import { CreateVirtualCharacterDto, UpdateVirtualCharacterDto } from './dto/virtual-character.dto';
import { v4 as uuidv4 } from 'uuid';
import { Appellation } from './entities/appellation.entity';
import { Relationship } from './entities/relationship.entity';
import { VoiceTone } from './entities/voice-tone.entity';
import { CharacterSetting } from './entities/character-setting.entity';
import { UserService } from '../user/user.service';


@Injectable()
export class VirtualCharacterService {
  constructor(
    @InjectRepository(VirtualCharacter)
    private virtualCharacterRepository: Repository<VirtualCharacter>,
    @InjectRepository(Appellation)
    private appellationRepository: Repository<Appellation>,
    @InjectRepository(Relationship)
    private relationshipRepository: Repository<Relationship>,
    @InjectRepository(VoiceTone)
    private voiceToneRepository: Repository<VoiceTone>,
    @InjectRepository(CharacterSetting)
    private characterSettingRepository: Repository<CharacterSetting>,
    private userService: UserService,
  ) {}

  async create(userId: string, createDto: CreateVirtualCharacterDto): Promise<VirtualCharacter> {
    const characterId = `vc_${uuidv4()}`;
    const character = this.virtualCharacterRepository.create({
      ...createDto,
      userId,
      characterId,
    });
    
    const savedCharacter = await this.virtualCharacterRepository.save(character);
    
    // 更新用户的虚拟人信息
    await this.userService.updateVirtualCharacterInfo(userId, characterId);
    
    return savedCharacter;
  }

  async findAllByUser(userId: string): Promise<VirtualCharacter[]> {
    return await this.virtualCharacterRepository.find({
      where: { userId, isActive: true },
    });
  }

  async findOne(userId: string, characterId: string): Promise<VirtualCharacter> {
    const character = await this.virtualCharacterRepository.findOne({
      where: { characterId, isActive: true },
    });

    if (!character) {
      throw new NotFoundException('Virtual character not found');
    }

    if (character.userId !== userId) {
      throw new UnauthorizedException('Not authorized to access this character');
    }

    return character;
  }

  async update(userId: string, characterId: string, updateDto: UpdateVirtualCharacterDto) {
    await this.virtualCharacterRepository.update({ characterId }, updateDto);
    return await this.findOne(userId, characterId);
  }

  async remove(userId: string, characterId: string): Promise<void> {
    const character = await this.findOne(userId, characterId);
    await this.virtualCharacterRepository.update(
      { characterId },
      { isActive: false }
    );
  }

  async findByRelationship(userId: string, relationship: string): Promise<VirtualCharacter[]> {
    return await this.virtualCharacterRepository.find({
      where: { userId, relationship, isActive: true },
    });
  }

  // 查询所有称呼
  async findAllAppellations() {
    return this.appellationRepository.find({
      select: ['id', 'name', 'description', 'isVip', 'priority'],
      order: {
        priority: 'DESC'
      }
    });
  }

  // 查询所有关系
  async findAllRelationships() {
    return this.relationshipRepository.find({
      select: ['id', 'name', 'description', 'intimacyLevel', 'isVip', 'priority'],
      order: {
        priority: 'DESC'
      }
    });
  }

  // 查询所有音色
  async findAllVoiceTones() {
    return this.voiceToneRepository.find({
      select: ['id', 'name', 'description', 'category', 'style', 'audioFile', 'isVip', 'priority'],
      order: {
        priority: 'DESC'
      }
    });
  }

  // 查询所有预设人设
  async findAllCharacterSettings() {
    return this.characterSettingRepository.find({
      select: [
        'id', 'name', 'age', 'gender', 'personality', 'background', 
        'hobbies', 'appearance', 'voiceStyle', 'voiceToneId', 'isVip', 'priority'
      ],
      order: {
        priority: 'DESC'
      }
    });
  }

  // 按分类查询音色
  async findVoiceTonesByCategory(category: string) {
    return this.voiceToneRepository.find({
      where: { category },
      select: ['id', 'name', 'description', 'style', 'audioFile', 'isVip', 'priority'],
      order: {
        priority: 'DESC'
      }
    });
  }

  // 查询VIP称呼
  async findVipAppellations() {
    return this.appellationRepository.find({
      where: { isVip: true },
      select: ['id', 'name', 'description', 'priority'],
      order: {
        priority: 'DESC'
      }
    });
  }

  // 查询VIP关系  
  async findVipRelationships() {
    return this.relationshipRepository.find({
      where: { isVip: true },
      select: ['id', 'name', 'description', 'intimacyLevel', 'priority'],
      order: {
        priority: 'DESC'
      }
    });
  }

  // 查询VIP音色
  async findVipVoiceTones() {
    return this.voiceToneRepository.find({
      where: { isVip: true },
      select: ['id', 'name', 'description', 'category', 'style', 'audioFile', 'priority'],
      order: {
        priority: 'DESC'
      }
    });
  }

  // 查询VIP人设
  async findVipCharacterSettings() {
    return this.characterSettingRepository.find({
      where: { isVip: true },
      select: [
        'id', 'name', 'age', 'gender', 'personality', 'background', 
        'hobbies', 'appearance', 'voiceStyle', 'voiceToneId', 'priority'
      ],
      order: {
        priority: 'DESC'
      }
    });
  }

  async findLatest(userId: string): Promise<VirtualCharacter> {
    return await this.virtualCharacterRepository.findOne({
      where: { userId, isActive: true },
      order: { updateTime: 'DESC' }
    });
  }
} 